package com.a1573595.musicplayer.dbHelper

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import com.a1573595.musicplayer.model.Music
import java.util.Locale

class OnLineMusicDatabaseHelper(context: Context) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {

    companion object {
        private const val DB_NAME = "OnLine_Music_Information.db"
        private const val DB_VERSION = 1
        private const val TABLE_NAME = "music"
        private const val CREATE_TABLE = """
            CREATE TABLE $TABLE_NAME (
                id INTEGER PRIMARY KEY,
                music_name TEXT NOT NULL,
                music_URL TEXT NOT NULL
            )
        """
    }

    override fun onCreate(db: SQLiteDatabase) {
        db.execSQL(CREATE_TABLE)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        db.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
        onCreate(db)
    }

    fun insertMusic(music: Music) {
        val db = writableDatabase
        val values = ContentValues().apply {
            put("id", music.id)
            put("music_name", music.musicName)
            put("music_URL", music.musicURL)
        }
        db.insert(TABLE_NAME, null, values)
        db.close()
    }

    fun findMusicByName(musicName: String): Music? {
        val db = readableDatabase
        val normalizedMusicName = musicName.trim().toLowerCase(Locale.ROOT)
        val cursor = db.query(
            TABLE_NAME,
            null,
            "LOWER(music_name) = ?",
            arrayOf(normalizedMusicName),
            null,
            null,
            null
        )
        var music: Music? = null
        if (cursor.moveToFirst()) {
            music = Music(
                id = cursor.getInt(cursor.getColumnIndexOrThrow("id")),
                musicName = cursor.getString(cursor.getColumnIndexOrThrow("music_name")),
                musicURL = cursor.getString(cursor.getColumnIndexOrThrow("music_URL"))
            )
        }
        cursor.close()
        db.close()
        return music
    }
}